package com.ffapp.helper.fragment.passageway;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.helper.R;
import com.ffapp.helper.basis.BasisFragment;
import com.ffapp.helper.basis.Constants;
import com.ffapp.helper.bean.ParamListData;
import com.ffapp.helper.home.HomeIndexActivity;
import com.ffapp.helper.util.CountDown;
import com.ffapp.helper.util.PassWayUtil;
import com.ffapp.helper.util.SoftKeyBoardListener;
import com.ffapp.helper.view.PopHandle;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import my.BleUtils;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link PassagewayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PassagewayFragment extends BasisFragment {
    private Spinner passageway, hardwareInterface;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private ArrayList<Fragment> list_fragment;
    private RSADCPropertiesFragment mRSADCProp;
    private RSParamFragment mRSParam;
    private ADCParamFragment mADCParam;
    private RSADCAlarmFragment mRSADCAlarm;
    private DIAlarmFragment mDIAlarm;
    private ChannelAdapter adapter;
    private HomeIndexActivity activity;

    private LinearLayout tablayoutLinLay;
    @BindView(R.id.btn_save)
    Button saveBtn;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();
    private StringBuffer result = new StringBuffer();

    ArrayList<ParamListData> submitList = new ArrayList<>();
    private boolean isFinish = false;
    private boolean isDestroy = false;

    String currentHardwareInterface = "无";

    private List<ParamListData> passWayOne = new ArrayList<>();
    private List<ParamListData> passWayTwo = new ArrayList<>();
    private List<ParamListData> passWayThree = new ArrayList<>();
    private List<ParamListData> passWayFour = new ArrayList<>();
    private List<ParamListData> passWayFive = new ArrayList<>();


    private List<List<ParamListData>> allPassWayList = new ArrayList<>();
    private PopHandle popHandle;

    private int subPosition = 0;
    private Handler submitHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 74:  //settingSave
                    try {
                        initSettingSaveThred();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    break;
                case 75:   //submit
                    isFinish = false;
                    if (subPosition < submitList.size()) {
                        submit(submitList.get(subPosition));
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if (!TextUtils.isEmpty(saveResult.toString())) {
                            if (popHandle == null) {
                                popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            }
                            popHandle.show();
                            if(type == Constants.AT_FROM_FILE){
                                activity.refresh();
                            }
                        } else {
                            showToast("保存成功");
                            PassWayUtil.setPassWayListChange(allPassWayList);
                        }
                    }
                    break;
                case 76:        // //检查是否传输完毕
                    try {
                        if (!isFinish && !isDestroy) {
                            isFinish = true;
                            showToast("设置失败，请重试");
                            dismissProgress();
                            BleUtils.stopNotify();
                        }
                    } catch (NullPointerException e) {
                        throw e;
                    }
                    break;
                case 79:
                    BleUtils.stopNotify();
                    isFinish = true;
                    dismissProgress();
                    mCountDownTimer.cancel();
                    break;
            }
        }
    };

    //tablayout的标题
    private String[] mTitles = new String[]{"通道属性", "通信参数", "报警参数"};

    static PassagewayFragment fragment;

    public static PassagewayFragment newInstance() {
        PassagewayFragment fragment = new PassagewayFragment();
        return fragment;
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_passageway);
        mTabLayout = (TabLayout) findViewById(R.id.id_tablayout);
        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        passageway = (Spinner) findViewById(R.id.passageway);
        hardwareInterface = (Spinner) findViewById(R.id.hardwareInterface);
        tablayoutLinLay = (LinearLayout) findViewById(R.id.ll_tablayout);

        mRSADCProp = new RSADCPropertiesFragment();
        mRSParam = new RSParamFragment();
        mADCParam = new ADCParamFragment();
        mRSADCAlarm = new RSADCAlarmFragment();
        mDIAlarm = DIAlarmFragment.newInstance();

        list_fragment = new ArrayList<>();
        adapter = new ChannelAdapter(getChildFragmentManager(), list_fragment);
        mViewPager.setAdapter(adapter);
        //TabLayout和ViewPager的关联
        mTabLayout.setupWithViewPager(mViewPager);
        initCountDownTimer();
        SoftKeyBoardListener.setListener(mContext, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                tablayoutLinLay.setVisibility(View.GONE);
                saveBtn.setVisibility(View.GONE);
            }

            @Override
            public void keyBoardHide(int height) {
                tablayoutLinLay.setVisibility(View.VISIBLE);
                saveBtn.setVisibility(View.VISIBLE);
            }
        });
        isDestroy = false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(76);
                //这时候可以做30秒的计时操作
            }

            @Override
            public void onTick(long millisUntilFinished) {

            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        activity = (HomeIndexActivity) getActivity();
        evenClick();
    }

    private String atShowString;
    private int type;
    private boolean passWaySpinnerSelect = true;

    private void evenClick() {
        System.out.println("eventClick");
        passageway.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                submitList = new ArrayList<>();
                String deviceInface = getDeviceInterface(position);
                if (TextUtils.isEmpty(deviceInface)) {
                    hardwareInterface.setSelection(0, true);
                } else {
                    setDeviceInterface(deviceInface);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        hardwareInterface.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {//选择item的选择点击监听事件
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {

                if (passWaySpinnerSelect == false) {
                    if (atShowString.contains(hardwareInterface.getSelectedItem().toString()) && !hardwareInterface.getSelectedItem().toString().contains("RS") && !hardwareInterface.getSelectedItem().toString().contains("无")) {
                        showToast(hardwareInterface.getSelectedItem().toString() + "端口被占用");
                        passWaySpinnerSelect = true;
                        hardwareInterface.setSelection(0, true);
                        return;
                    }
                }
                passWaySpinnerSelect = false;
                list_fragment.clear();
                //下面这个表 根据arrays.xml   中      <string-array name="yInterface">  里面的值对应
                String[] yInterface = getResources().getStringArray(R.array.yInterface);
                currentHardwareInterface = yInterface[arg2];
                switch (yInterface[arg2]) {
                    case "无":
                        mTitles = new String[]{};
                        break;
                    case "RS485-1":
                    case "RS485-2":
                    case "RS485-3":
                    case "RS232-1":
                    case "LORA":
                        mTitles = new String[]{"报警参数", "通道属性", "通信参数"};
                        mRSADCAlarm = RSADCAlarmFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mRSADCAlarm);

                        mRSADCProp = RSADCPropertiesFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mRSADCProp);

                        mRSParam = RSParamFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mRSParam);

                        break;
                    case "ADC0":
                    case "ADC1":
                    case "ADC2":
                    case "ADC3":
                    case "ADC4":
                    case "ADC5":
                        mTitles = new String[]{"报警参数", "通道属性", "通信参数"};
                        mRSADCAlarm = RSADCAlarmFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mRSADCAlarm);

                        mRSADCProp = RSADCPropertiesFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mRSADCProp);

                        mADCParam = ADCParamFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mADCParam);
                        break;
                    case "RainFall":
                        mTitles = new String[]{"报警参数", "通道属性"};
                        mRSADCAlarm = RSADCAlarmFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mRSADCAlarm);

                        mRSADCProp = RSADCPropertiesFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mRSADCProp);
                        break;
                    case "DI0":
                    case "DI1":
                    case "DI2":
                    case "DI3":
                        mTitles = new String[]{"报警参数"};
                        mDIAlarm = DIAlarmFragment.newInstance(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                        list_fragment.add(mDIAlarm);
                        break;
                }
                adapter.notifyDataSetChanged();
                mViewPager.setOffscreenPageLimit(list_fragment.size());

            }

            public void onNothingSelected(AdapterView<?> arg0) {
                System.out.println("onNothingSelected");
            }
        });
    }


    private boolean isFist = true;

    public void setList(String atShowString, int type) {
        this.atShowString = atShowString;
        this.type = type;
        for (List<ParamListData> listData : allPassWayList) {
            listData.clear();
        }
        allPassWayList.clear();
        initAtShow(atShowString, type);
        if (isFist) {
            setDeviceInterface(getDeviceInterface(passageway.getSelectedItemPosition()));
            isFist = false;
        } else {
            setDeviceInterface(getDeviceInterface(passageway.getSelectedItemPosition()));
            switch (currentHardwareInterface) {
                case "RS485-1":
                case "RS485-2":
                case "RS485-3":
                case "RS232-1":
                case "LORA":
                    mRSADCAlarm.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    mRSADCProp.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    mRSParam.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    break;
                case "ADC0":
                case "ADC1":
                case "ADC2":
                case "ADC3":
                case "ADC4":
                case "ADC5":
                    mRSADCAlarm.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    mRSADCProp.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    mADCParam.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    break;
                case "RainFall":
                    mRSADCAlarm.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    mRSADCProp.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                case "DI0":
                case "DI1":
                case "DI2":
                case "DI3":
                    mDIAlarm.readData(currentHardwareInterface, allPassWayList.get(passageway.getSelectedItemPosition()));
                    break;
            }
        }
    }

    private void initAtShow(String sMsgObjString, int type) {
        if (sMsgObjString != null && sMsgObjString.trim().length() > 0) {
            boolean dataFromFile = false;
            if (type != Constants.AT_FROM_DEVICE) {
                dataFromFile = true;
            }
            PassWayUtil.initPassWayData(sMsgObjString, getContext(), "HW Chn1:", "CH1 Com Cfg:", "CH1 filter mode:", "CH1 crc mode", passWayOne, dataFromFile);
            PassWayUtil.initPassWayData(sMsgObjString, getContext(), "HW Chn2:", "CH2 Com Cfg:", "CH2 filter mode:", "CH2 crc mode", passWayTwo, dataFromFile);
            PassWayUtil.initPassWayData(sMsgObjString, getContext(), "HW Chn3:", "CH3 Com Cfg:", "CH3 filter mode:", "CH3 crc mode", passWayThree, dataFromFile);
            PassWayUtil.initPassWayData(sMsgObjString, getContext(), "HW Chn4:", "CH4 Com Cfg:", "CH4 filter mode:", "CH4 crc mode", passWayFour, dataFromFile);
            PassWayUtil.initPassWayData(sMsgObjString, getContext(), "HW Chn5:", "CH5 Com Cfg:", "CH5 filter mode:", "CH5 crc mode", passWayFive, dataFromFile);
            allPassWayList.add(passWayOne);
            allPassWayList.add(passWayTwo);
            allPassWayList.add(passWayThree);
            allPassWayList.add(passWayFour);
            allPassWayList.add(passWayFive);
        }
    }

    private String getDeviceInterface(int position) {
        String deviceInface = "";
        if (allPassWayList.size() < 1) {
            return deviceInface;
        }
        deviceInface = PassWayUtil.getDeviceInface(allPassWayList.get(position));
        return deviceInface;
    }

    private void setDeviceInterface(String deviceInface) {
        SpinnerAdapter apsAdapter = hardwareInterface.getAdapter();
        int count = apsAdapter.getCount();
        for (int i = 0; i < count; i++) {
            if (deviceInface.equals(apsAdapter.getItem(i).toString())) {
                passWaySpinnerSelect = true;
                hardwareInterface.setSelection(0, true);
                hardwareInterface.setSelection(i, true);
                break;
            }
        }
    }

    @OnClick(R.id.btn_save)
    public void save() {
        submitList.clear();
        saveResult.setLength(0);
        result.setLength(0);
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                subPosition = 0;
                submitHandler.sendEmptyMessage(Constants.SETSAVE);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    result.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(result.toString());
                if (sMes.contains("OK")) {
                    result.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    result.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(curParamListData.getName() + "保存失败" + "\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });

    }

    public void initSettingSaveThred() throws UnsupportedEncodingException {
        String sPassageWay = passageway.getSelectedItem().toString();
        sPassageWay = sPassageWay.substring(2);
        String interfaces = hardwareInterface.getSelectedItem().toString();
        boolean haveValueList = false;
        List<ParamListData> passWayList = null;
        switch (type){
            case Constants.AT_FROM_DEVICE:
                passWayList = allPassWayList.get(Integer.valueOf(sPassageWay) - 1);
                haveValueList = PassWayUtil.getSubmitList(sPassageWay, interfaces, passWayList, submitList);
                break;
            case  Constants.AT_FROM_FILE:
                haveValueList = true;
                for (int i = 0;i<allPassWayList.size();i++){
                    ParamListData data = allPassWayList.get(i).get(0);
                    interfaces = TextUtils.isEmpty(data.getValue()) ? data.getKey() : data.getValue();
                    if(!TextUtils.isEmpty(interfaces)){
                        PassWayUtil.getSubmitList(""+(i+1),interfaces,allPassWayList.get(i), submitList);
                    }
                }
                break;
        }

        if (!haveValueList) {
            dismissProgress();
            return;
        }
        submitHandler.sendEmptyMessage(Constants.SUBMIT);
    }


    private ParamListData curParamListData;

    public void submit(final ParamListData terminalData) {
        curParamListData = terminalData;
        mCountDownTimer.start();
        BleUtils.write(terminalData.getValue(), new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {

                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                showToast("提交失败，请重试");
                submitHandler.sendEmptyMessage(Constants.END);
            }
        });
    }

    class ChannelAdapter extends FragmentStatePagerAdapter {
        private ArrayList<Fragment> fragments;
        private FragmentManager fm;

        public ChannelAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
            super(fm);
            this.fm = fm;
            this.fragments = fragments;
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
        }


        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragments.get(arg0);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestroy = true;
        isFinish = true;
        BleUtils.stopNotify();
        mCountDownTimer.cancel();
    }
}
